package com.lse_from.utils

import com.lse_from.component.Slf4j.Companion.log
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.util.LinkedMultiValueMap
import org.springframework.util.MultiValueMap
import org.springframework.web.client.RestTemplate
import java.net.http.HttpClient
import java.nio.charset.Charset

/**
 * restTemplate 工具
 */
class RestUtil {

    companion object {

        val headerMap = hashMapOf(
            "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36",
            "Content-Type" to "application/x-www-form-urlencoded",
        )

        /**
         * @param url url地址
         * @param params 参数
         * @param headers 头
         * @param type 0.GET 1.POST
         * @param clazz 返回参数的封装
         */
        fun <T> send(
            url: String,
            param: HashMap<String, String>?,
            header: HashMap<String, String>?,
            type: Int,
            clazz: Class<T>
        ): ResponseEntity<T> {

            val rest = RestTemplate()

            val headers: MultiValueMap<String, String> = LinkedMultiValueMap<String, String>()

            val params: MultiValueMap<String, String> = LinkedMultiValueMap()

            if (header != null && header.isNotEmpty()) {
                header.forEach { k, v -> headers.set(k, v) }
            } else {
                headerMap.forEach { k, v -> headers.set(k, v) }
            }

            if (param != null && param.isNotEmpty()) {
                param.forEach { k, v -> params.set(k, v) }
            }

            val entity = HttpEntity<MultiValueMap<String, String>>(params, headers)

            var method = HttpMethod.GET
            when (type) {
                0 -> {
                    method = HttpMethod.GET
                }
                1 -> {
                    method = HttpMethod.POST
                }
            }

            val result = rest.exchange(url, method, entity, clazz)

//            println(result)

            return result
        }
    }

}

fun main() {
    RestUtil.send("http://dyxs12.com/paly-195979-1-1/", null, null, 0, String::class.java)
}
